package com.css.zfzx.sjcj.modules.hddcB1GeomorLnHasGeoSvyPt.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnHasGeoSvyPt.repository.HddcB1GeomorlnhasgeosvyptNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnHasGeoSvyPt.repository.HddcB1GeomorlnhasgeosvyptRepository;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnHasGeoSvyPt.repository.entity.HddcB1GeomorlnhasgeosvyptEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnHasGeoSvyPt.service.HddcB1GeomorlnhasgeosvyptService;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnHasGeoSvyPt.viewobjects.HddcB1GeomorlnhasgeosvyptQueryParams;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnHasGeoSvyPt.viewobjects.HddcB1GeomorlnhasgeosvyptVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author zhangcong
 * @date 2020-11-30
 */
@Service
public class HddcB1GeomorlnhasgeosvyptServiceImpl implements HddcB1GeomorlnhasgeosvyptService {

	@Autowired
    private HddcB1GeomorlnhasgeosvyptRepository hddcB1GeomorlnhasgeosvyptRepository;
    @Autowired
    private HddcB1GeomorlnhasgeosvyptNativeRepository hddcB1GeomorlnhasgeosvyptNativeRepository;

    @Override
    public JSONObject queryHddcB1Geomorlnhasgeosvypts(HddcB1GeomorlnhasgeosvyptQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcB1GeomorlnhasgeosvyptEntity> hddcB1GeomorlnhasgeosvyptPage = this.hddcB1GeomorlnhasgeosvyptNativeRepository.queryHddcB1Geomorlnhasgeosvypts(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcB1GeomorlnhasgeosvyptPage);
        return jsonObject;
    }


    @Override
    public HddcB1GeomorlnhasgeosvyptEntity getHddcB1Geomorlnhasgeosvypt(String id) {
        HddcB1GeomorlnhasgeosvyptEntity hddcB1Geomorlnhasgeosvypt = this.hddcB1GeomorlnhasgeosvyptRepository.findById(id).orElse(null);
         return hddcB1Geomorlnhasgeosvypt;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB1GeomorlnhasgeosvyptEntity saveHddcB1Geomorlnhasgeosvypt(HddcB1GeomorlnhasgeosvyptEntity hddcB1Geomorlnhasgeosvypt) {
        String uuid = UUIDGenerator.getUUID();
        hddcB1Geomorlnhasgeosvypt.setUuid(uuid);
        hddcB1Geomorlnhasgeosvypt.setCreateUser(PlatformSessionUtils.getUserId());
        hddcB1Geomorlnhasgeosvypt.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcB1Geomorlnhasgeosvypt.setIsValid("1");
        this.hddcB1GeomorlnhasgeosvyptRepository.save(hddcB1Geomorlnhasgeosvypt);
        return hddcB1Geomorlnhasgeosvypt;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB1GeomorlnhasgeosvyptEntity updateHddcB1Geomorlnhasgeosvypt(HddcB1GeomorlnhasgeosvyptEntity hddcB1Geomorlnhasgeosvypt) {
        UpdateUtil.copyNullProperties(hddcB1GeomorlnhasgeosvyptRepository.findByUuidAndIsValid(hddcB1Geomorlnhasgeosvypt.getUuid(), "1"), hddcB1Geomorlnhasgeosvypt);
        hddcB1Geomorlnhasgeosvypt.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB1Geomorlnhasgeosvypt.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB1GeomorlnhasgeosvyptRepository.save(hddcB1Geomorlnhasgeosvypt);
        return hddcB1Geomorlnhasgeosvypt;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB1Geomorlnhasgeosvypts(List<String> ids) {
        List<HddcB1GeomorlnhasgeosvyptEntity> hddcB1GeomorlnhasgeosvyptList = this.hddcB1GeomorlnhasgeosvyptRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcB1GeomorlnhasgeosvyptList) && hddcB1GeomorlnhasgeosvyptList.size() > 0) {
            for(HddcB1GeomorlnhasgeosvyptEntity hddcB1Geomorlnhasgeosvypt : hddcB1GeomorlnhasgeosvyptList) {
//                this.hddcB1GeomorlnhasgeosvyptRepository.delete(hddcB1Geomorlnhasgeosvypt);
                hddcB1Geomorlnhasgeosvypt.setIsValid("0");
                hddcB1Geomorlnhasgeosvypt.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB1Geomorlnhasgeosvypt.setUpdateTime(new Date());
                this.hddcB1GeomorlnhasgeosvyptRepository.save(hddcB1Geomorlnhasgeosvypt);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcB1GeomorlnhasgeosvyptQueryParams queryParams, HttpServletResponse response) {
        List<HddcB1GeomorlnhasgeosvyptEntity> yhDisasterEntities = hddcB1GeomorlnhasgeosvyptNativeRepository.exportYhDisasters(queryParams);
        List<HddcB1GeomorlnhasgeosvyptVO> list=new ArrayList<>();
        for (HddcB1GeomorlnhasgeosvyptEntity entity:yhDisasterEntities) {
            HddcB1GeomorlnhasgeosvyptVO yhDisasterVO=new HddcB1GeomorlnhasgeosvyptVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"地貌线与地质地貌点关联表","地貌线与地质地貌点关联表",HddcB1GeomorlnhasgeosvyptVO.class,"地貌线与地质地貌点关联表.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcB1GeomorlnhasgeosvyptVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB1GeomorlnhasgeosvyptVO.class, params);
            List<HddcB1GeomorlnhasgeosvyptVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcB1GeomorlnhasgeosvyptVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcB1GeomorlnhasgeosvyptVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcB1GeomorlnhasgeosvyptVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcB1GeomorlnhasgeosvyptEntity yhDisasterEntity = new HddcB1GeomorlnhasgeosvyptEntity();
            HddcB1GeomorlnhasgeosvyptVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcB1Geomorlnhasgeosvypt(yhDisasterEntity);
        }
    }

}
